#include <REGX52.H>
#include <intrins.h>


#define data_msg P0


sbit RS = P1^0;
sbit RW = P1^1;
sbit E  = P1^4;


void busy_check(){

	int tmp = 0x80;
	data_msg = 0x80;
	while(tmp & data_msg){
	RS = 0;
	RW = 1;
	E = 0;
	_nop_();
	E = 1;
	_nop_();
	tmp = data_msg;
	E = 0;
	_nop_();
	}
}

void write_data(char msg){

	busy_check();
	RS = 1;
	RW = 0;
	E  = 0;
	_nop_();
	data_msg = msg;
	E = 1;
	_nop_();
	E = 0;
	_nop_();

}

void write_cmd(char cmd){

	busy_check();
	RS = 0;
	RW = 0;
	E = 0;
	_nop_();
	data_msg = cmd;
	_nop_();
	E = 1;
	_nop_();
	E = 0;
	_nop_();
}

void write_string(int row,int col,char *string){

	busy_check();
	switch(row){
	
		case 1:
			write_cmd(0x80 + col);
		while(*string){
			write_data(*string);
			string++;
		}
		break;
		case 2:
			write_cmd(0x80 + 0x40 + col);
		while(*string){
			write_data(*string);
			string++;
		}
		break;
	}
}

void Delay15ms()		//@11.0592MHz
{
	unsigned char i, j;

	i = 27;
	j = 226;
	do
	{
		while (--j);
	} while (--i);
}

void Delay5ms()		//@11.0592MHz
{
	unsigned char i, j;

	i = 9;
	j = 244;
	do
	{
		while (--j);
	} while (--i);
}

void Init_lcd1602(){

	//（1）延时 15ms
	Delay15ms();
	//（2）写指令 38H(不检测忙信号)
	write_cmd(0x38);
	//（3）延时 5ms
	Delay5ms();
	//（4）以后每次写指令，读/写数据操作均需要检测忙信号
	busy_check();
	//（5）写指令 38H：显示模式设置
	write_cmd(0x38);
	//（6）写指令 08H：显示关闭
	write_cmd(0x08);
	//（7）写指令 01H：显示清屏
	write_cmd(0x01);
	//（8）写指令 06H：显示光标移动设置
	write_cmd(0x06);
	//（9）写指令 0CH：显示开及光标设置
	write_cmd(0x0c);
}

int main(){

	Init_lcd1602();
	write_string(1,5,"NO1");
	write_string(2,1,"successful test");
	
	
	return 0;
}